const { defineConfig } = require("@vue/cli-service");
let { list } = require("./src/mock");
const bodyParser = require("body-parser");
const Mock = require("mockjs");
const jwt = require("jsonwebtoken");
const key = "rdligkfnwlmkefa";
const userList = [
  {
    username: "admin",
    password: "admin",
    role: "admin",
    nickname: "管理员",
    avator: Mock.mock("@image(50x50, @color, 管理员)"),
  },
  {
    username: "13111111111",
    password: "666666",
    role: "user",
    nickname: "普通用户",
    avator: Mock.mock("@image(50x50, @color, 普通用户)"),
  },
];

module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    setupMiddlewares(middle, { app }) {
      app.use(bodyParser.json());
      // 列表请求
      app.get("/api/list", (req, res) => {
        const { pageCode = 1, pageSize = 10, wd = "" } = req.query;

        // 筛选之后的数据
        const newList = list.filter((v) => {
          return (
            v.id.includes(wd) ||
            v.name.includes(wd) ||
            v.address.includes(wd) ||
            v.title.includes(wd)
          );
        });

        res.send({
          code: 200,
          // 分页
          data: newList.slice((pageCode - 1) * pageSize, pageCode * pageSize),
          // 总个数
          total: newList.length,
        });
      });
      // 删除请求(支持单项多想删除)
      // id: 格式要求 id
      // id: 格式要求 id,id,id,id.id
      // 比如我要删除 1
      // /api/list/1
      // 比如我要删除 1    2     3     4
      // /api/list/1,2,3,4

      app.delete("/api/list/:id", (req, res) => {
        // 获取动态路由参数
        const { id } = req.params;
        // 过滤id
        list = list.filter((v) => !id.includes(v.id));
        // 返回
        res.send({
          code: 200,
          message: "删除成功！！",
        });
      });

      // 列表添加
      app.post("/api/list", (req, res) => {
        // 获取添加数据
        const item = req.body;
        // 给数据添加id 字段
        item.id = Math.random().toString().slice(2);
        // 头部插入数据
        list.unshift(item);
        // 返回结果
        res.send({
          code: 200,
          message: "添加成功！！",
        });
      });

      // 列表编辑接口
      app.post("/api/list/edit", (req, res) => {
        const { id } = req.body;

        const item = list.find((v) => v.id === id);

        Object.assign(item, req.body);

        res.send({
          code: 200,
          message: "修改成功！！",
        });
      });
      // 登录
      app.post("/api/login", (req, res) => {
        const { username, password } = req.body;
        const user = userList.find(
          (v) => v.username === username && v.password === password
        );
        if (user) {
          res.send({
            message: `登录成功， 欢迎${user.nickname}用户`,
            data: {
              role: user.role,
              nickname: user.nickname,
              avator: user.avator,
              token: jwt.sign(
                {
                  role: user.role,
                  nickname: user.nickname,
                  avator: user.avator,
                },
                key
              ),
            },
          });
        } else {
          res.status(401).send({
            message: "登录失败, 账户密码错误",
          });
        }
      });

      // 图标接口
      app.get("/api/echarts/age", (req, res) => {
        const data = [0, 0, 0];

        list.forEach((v) => {
          if (v.age >= 18 && v.age <= 26) {
            data[0]++;
          } else if (v.age >= 27 && v.age <= 35) {
            data[1]++;
          } else {
            data[2]++;
          }
        });

        res.send({
          code: 200,
          data: {
            title: {
              text: "年龄人群分布",
            },
            tooltip: {},
            xAxis: {
              data: ["18-26", "27-35", "36-50"],
            },
            yAxis: {},
            series: [
              {
                name: "年龄分布",
                type: "bar",
                data,
              },
            ],
          },
        });
      });

      // token 验证接口
      app.get("/api/user/info/:token", (req, res) => {
        const { token } = req.params;

        try {
          const data = jwt.verify(token, key);
          res.send({
            code: 200,
            data: data,
          });
        } catch {
          res.send({
            code: 403,
            message: "非法token!!!",
          });
        }
      });
      return middle;
    },
  },
});
